<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="客户经理">
                <a-input v-model="queryParam.userKeyword" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="加盟商">
                <a-input v-model="queryParam.franchiseeName" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select v-model="queryParam.status" placeholder="请选择">
                  <a-select-option value="1">启用</a-select-option>
                  <a-select-option value="2">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' } || {}">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-if="btnsPurviewData.add.isShow">新建</a-button>
        <!-- <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
        </a-dropdown> -->
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="custMagerId"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto"
        listName="custMagerList"
        :scroll="{ x: 'calc(1000px + 100%)' }"
        v-if="btnsPurviewData.query.isShow"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <div slot="userInfo" slot-scope="text, record">
          <div>{{ record.userName }}</div>
          <div>{{ record.userMobile }}</div>
        </div>
        <span slot="logoUrl" slot-scope="text">
          <img class="bannerImg" :src="text" v-if="text" />
        </span>
        <span slot="qrCode" slot-scope="text">
          <img class="bannerImg" :src="text" v-if="text" />
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <span v-if="btnsPurviewData.update.isShow">
              <a @click="handleEdit(record)">修改</a>
              <a-divider type="vertical" />
            </span>
            <span v-if="btnsPurviewData.editStatus.isShow">
              <a @click="handleChangeStatus(record)">{{ record.status == 1 ? '冻结' : '启用' }}</a>
              <a-divider type="vertical" />
            </span>
            <a @click="handleDel(record)" v-if="btnsPurviewData.delete.isShow">删除</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :title="formTitle"
        @cancel="handleCancel"
        @ok="_submit"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { BTNS_PURVIEW_MAP } from '@/store/mutation-types'
import storage from 'store'
import { STable, Ellipsis } from '@/components'
import {
  getCustMagerList,
  addCustMager,
  updateCustMager,
  delCustMager,
  editCustMagerStatus,
  getCustMagerDtl
} from '@/api/franchiseeManage'
import CreateForm from './modules/CreateCustMagerForm'
const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
    align: 'center',
    fixed: 'left',
    width: 80
  },
  {
    title: '客户经理信息',
    scopedSlots: { customRender: 'userInfo' },
    align: 'center'
  },
  {
    title: '加盟商名称',
    dataIndex: 'franchiseeName',
    align: 'center'
  },
  {
    title: '图片',
    dataIndex: 'logoUrl',
    scopedSlots: { customRender: 'logoUrl' },
    align: 'center'
  },
  {
    title: '职称',
    dataIndex: 'userTitle',
    align: 'center'
  },
  {
    title: '微信号',
    dataIndex: 'wechat',
    align: 'center'
  },
  {
    title: '二维码',
    dataIndex: 'qrCode',
    scopedSlots: { customRender: 'qrCode' },
    align: 'center'
  },
  {
    title: '简介',
    dataIndex: 'introduce',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '商户数',
    dataIndex: 'merchantNums',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '合同数',
    dataIndex: 'contractNums',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '合同总金额（元）',
    dataIndex: 'contractAmount',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '合同还款金额（元）',
    dataIndex: 'contractRepaymentAmount',
    customRender: (text) => text || '—',
    align: 'center'
  },

  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    fixed: 'right'
  }
]

const statusMap = {
  1: {
    status: 'processing',
    text: '启用'
  },
  2: {
    status: 'default',
    text: '冻结'
  }
}

export default {
  name: 'CustMagerList',
  components: {
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      btnsPurviewMap: storage.get(BTNS_PURVIEW_MAP),
      btnsPurviewData: {},
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getCustMagerList(requestParameters)
          .then((res) => {
            return res.result
          })
          .catch((e) => {})
      },
      selectedRowKeys: [],
      selectedRows: [],
      formTitle: '新建客户经理'
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    this.btnsPurviewData = this.btnsPurviewMap[this.$route.meta.permission[0]]
  },
  computed: {},
  methods: {
    /**
     * 新建/修改客户经理
     */
    _submit () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      console.log(form, 'form')
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.custMagerId) {
            // 修改 e.g.
            console.log(form.getFieldsValue())
            updateCustMager(form.getFieldsValue())
              .then((res) => {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()
                this.$message.info('修改成功')
              })
              .catch((e) => {
                this.confirmLoading = false
              })
          } else {
            // 新增
            addCustMager(values)
              .then((res) => {
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()
                this.$message.info('新增成功')
              })
              .catch((e) => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    /**
     * 新增客户经理
     */
    handleAdd () {
      this.mdl = null
      this.visible = true
      this.formTitle = '新建客户经理'
    },
    /**
     * 修改客户经理
     */
    handleEdit (record) {
      this.visible = true
      this.formTitle = '修改客户经理'
      getCustMagerDtl({ custMagerId: record.custMagerId })
        .then((res) => {
          this.mdl = { ...res.result }
        })
        .catch((e) => {})
    },
    /**
     * 删除客户经理
     */
    handleDel (record) {
      this.$warning({
        title: '删除提示',
        content: `确认删除${record.userName}?`,
        okText: '确认',
        cancelText: '取消',
        destroyOnClose: true,
        closable: true,
        onOk: () => {
          delCustMager({
            custMagerList: [
              {
                custMagerId: record.custMagerId
              }
            ]
          })
            .then((res) => {
              this.$refs.table.refresh()
              this.$message.info('删除成功')
            })
            .catch((e) => {})
        }
      })
    },
    /**
     * 切换客户经理状态
     */
    handleChangeStatus (record) {
      const params = { status: record.status === 1 ? 2 : 1, custMagerList: [{ custMagerId: record.custMagerId }] }
      editCustMagerStatus(params)
        .then((res) => {
          this.$refs.table.refresh()
          this.$message.info(`${record.status === 1 ? '冻结' : '启用'}成功`)
        })
        .catch((e) => {})
    },
    /**
     * 取消表单
     */
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    }
  }
}
</script>
<style lang="less" scoped>
.bannerImg {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}
</style>
